/************************************************************
 *  * EaseMob CONFIDENTIAL
 * __________________
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * NOTICE: All information contained herein is, and remains
 * the property of EaseMob Technologies.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from EaseMob Technologies.
 */

#import "ChatListViewController.h"
#import "SRRefreshView.h"
#import "ChatListCell.h"
#import "EMSearchBar.h"
#import "NSDate+Category.h"
#import "RealtimeSearchUtil.h"
#import "ChatViewController.h"
#import "EMSearchDisplayController.h"
#import "ConvertToCommonEmoticonsHelper.h"
#import "CallApplyViewController.h"
//#import "MLDate.h"
#import "FriendsViewController.h"
#import "FriendApplyViewController.h"
#import "SweetheartApplyViewController.h"
#import "MLTabBar.h"

@interface ChatListViewController ()<UITableViewDelegate,UITableViewDataSource, UISearchDisplayDelegate,SRRefreshDelegate, UISearchBarDelegate, IChatManagerDelegate,ChatViewControllerDelegate>

@property (strong, nonatomic) NSMutableArray        *dataSource;

@property (strong, nonatomic) UITableView           *tableView;
@property (nonatomic, strong) EMSearchBar           *searchBar;
@property (nonatomic, strong) SRRefreshView         *slimeView;

@property (strong, nonatomic) EMSearchDisplayController *searchController;

// 聊天列表的用户信息,字典里面是字典,字典里面只包含了,名字,头像的url


// 发起的约会列表
@property (nonatomic, strong) NSMutableArray *dateLaunchList;

// 约会申请列表
@property (nonatomic, strong) NSMutableArray *dateApplyList;



@end
static ChatListViewController *chatLVC;
@implementation ChatListViewController
{
    Utils * promptView;
    NSInteger msgUnreadCount;
    NSInteger userCount;
    UIView *headErrorView;

}
+(ChatListViewController *)shareChatListViewController
{
    @synchronized(self) {
        if (!chatLVC) {
            chatLVC = [[ChatListViewController alloc] init];
        }
        return chatLVC;
    }
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _dataSource = [NSMutableArray array];
    }
    return self;
}

-(void)rightItem
{
   // [AVAnalytics event:@"点击恋人页"]; // 通知服务器一个点击事件。

    [Utils pushTabbarHidden:[[FriendsViewController alloc] init] Selfvc:self];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"消息";

    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:NO];
    [self removeEmptyConversationsFromDB];
    
   // UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithTitle:@"好友" style:UIBarButtonItemStylePlain target:self action:@selector(rightItem)];
   // self.navigationItem.rightBarButtonItem = rightItem;
    
//    UIButton *leftBt = [UIButton buttonWithType:UIButtonTypeCustom];
//    [leftBt sizeToFit];
//    [leftBt setTitle:@"返回" forState:UIControlStateNormal];
//    [leftBt setContentMode:UIViewContentModeCenter];
//    [leftBt setImage:[UIImage imageNamed:@"back_normal"] forState:UIControlStateNormal];
//    [leftBt setImageEdgeInsets:UIEdgeInsetsMake(-2,-18, -2, 0)];
//    [leftBt setTitleEdgeInsets:UIEdgeInsetsMake(0, -12, 0, -10)];
//    leftBt.titleLabel.font = kFont(17);
//    leftBt.frame = CGRectMake(0, 0, 40, 30);
//    leftBt.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
//    [leftBt addTarget:self action:@selector(clickLeftBt) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *leftBarBt = [[UIBarButtonItem alloc] initWithCustomView:leftBt];
//    self.navigationItem.leftBarButtonItems = @[leftBarBt];
    
    
//    [self.view addSubview:self.searchBar];
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.slimeView];
    
//    [self searchController];


//    [self.view addSubview:headErrorView];
//    headErrorView.hidden = YES;
    
    promptView = [[Utils alloc]init];
    [promptView viewControllerPrompt:self.view.bounds Text:@"没有新的会话~" Image:[UIImage imageNamed:@"xinlianren_nul"]];
    promptView.viewPrompt.alpha = 0;
    [self.view addSubview:promptView.viewPrompt];
        //根据数据处理信息
    //[self judgeChatData];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cmd:) name:@"cmd" object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logOutSucceed) name:@"logOutSucceed" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(isLoveVC:) name:@"isLoveVC" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addChatterUsers:) name:@"addChatterUsers" object:nil];
    
}
- (void)addChatterUsers:(NSNotification *)notification
{
    NSDictionary *dic=[notification userInfo];
    MLUser *chatUser = (MLUser *)[dic objectForKey:@"user"];
    [[ShareData shareData].chatterUsers setObject:chatUser forKey:chatUser.objectId];
    [Utils saveChatUserDataNicknameUser:chatUser];
    
}
- (void)isLoveVC:(NSNotification *)notification
{
    NSDictionary *dic=[notification userInfo];
    MLUser *chatUser = (MLUser *)[dic objectForKey:@"user"];
    [self startPrivateChat:chatUser];
}
- (void)logOutSucceed
{
    [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:NO];
    [self removeEmptyConversationsFromDB];
}
-(void)cmd:(NSNotification *)notification
{
    NSDictionary *dic=[notification userInfo];
    EMMessage *message = [dic objectForKey:@"message"];
    if (message.messageBodies&&message.messageBodies.count) {
        EMCommandMessageBody *body= message.messageBodies.lastObject;
       if (body.action&&[body.action isEqualToString:ACTION_NEW_UPDATE_PROFILE]) {
            [self changePortraitObjectId:message.from];
        }
    }
    
}
//收到好友换头像
- (void)changePortraitObjectId:(NSString *)objectId
{
    if ([ShareData shareData].chatterUsers.count) {
        MLUser *user = [[ShareData shareData].chatterUsers objectForKey:objectId];
        if (user&&user.objectId) {
            AVQuery *query = [MLUser query];
            [query whereKey:@"objectId" equalTo:user.objectId];
            [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                MLUser *nUser = (MLUser *)object;
               [[ShareData shareData].chatterUsers setObject:nUser forKey:nUser.objectId];
                 [Utils saveChatUserDataNicknameUser:nUser];
                [self.tableView reloadData];
                
            }];
        }
    }
}

//根据数据处理信息
- (void)judgeChatData
{
    NSLog(@"123");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

//-(void)didReceiveMessage:(EMMessage *)message
//{
//   // [self viewWillAppear:YES];
//}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (![[EaseMob sharedInstance].chatManager isConnected]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginEaseMob" object:self userInfo:nil];
        
    }
    // 加载约会申请列表
   // [self loadDateList];
    
    [self refreshDataSource];
    [self registerNotifications];
    
    UIView *Badge = (UIView*)[self.tabBarController.tabBar viewWithTag:100000+2];
    if (Badge.alpha == 1) {
        [Utils Hidden:Badge Bool:NO];
    }
     [[EaseMob sharedInstance].chatManager removeConversationByChatter:@"new_chat_apply" deleteMessages:YES append2Chat:YES];
   // [self shipChatApply];
}
//无效
//- (void)shipChatApply
//{
//    ////拉黑通话申请
//    NSString *str = [NSString stringWithFormat:@"shipChatApply%@",[MLUser currentUser].objectId];
//    BOOL wasShown = [[NSUserDefaults standardUserDefaults] boolForKey:str];
//    if (wasShown) {
//        
//    } else {
//        EMError *error = [[EaseMob sharedInstance].chatManager blockBuddy:@"NEW_CHAT_APPLY" relationship:eRelationshipFrom];
//        if (!error) {
//            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:str];
//            //删除回话
//            [[EaseMob sharedInstance].chatManager removeConversationByChatter:@"NEW_CHAT_APPLY" deleteMessages:YES append2Chat:YES];
//        }
//    }
//}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self unregisterNotifications];
}

-(void)laixiaoxi
{
    if (self.dataSource.count != userCount) {
        userCount = self.dataSource.count;
        NSMutableArray *userIds = [[NSMutableArray alloc]init];
        BOOL isQuery = NO;
        for (EMConversation *conversation in self.dataSource) {
            [userIds addObject:conversation.chatter];
            [Utils saveChatUserObjectID:conversation.chatter];
            MLUser *user = [[ShareData shareData].chatterUsers objectForKey:conversation.chatter];
            if(user){
                
            }else{
               isQuery = YES;
            }
        }
        if (isQuery == YES) {
            AVQuery *userQuery = [MLUser query];
            [userQuery whereKey:@"objectId" containedIn:userIds];
            userQuery.limit = 1000;
            userQuery.cachePolicy = kAVCachePolicyNetworkElseCache;
            userQuery.maxCacheAge = 7200;
            [userQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                if (!error) {
                    for (MLUser *user in objects) {
                        [[ShareData shareData].chatterUsers setObject:user forKey:user.objectId];
                         [Utils saveChatUserDataNicknameUser:user];
                    }
                    msgUnreadCount = 0;
                    [self.tableView reloadData];
                    self.title = @"消息";
                }else{
                    
                }
                
            }];
        }else{
            self.title = @"消息";
        }
    };
}


- (void)removeEmptyConversationsFromDB
{
    NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations];
    NSMutableArray *needRemoveConversations;
    for (EMConversation *conversation in conversations) {
        if (!conversation.latestMessage || (conversation.conversationType == eConversationTypeChatRoom)) {
            if (!needRemoveConversations) {
                needRemoveConversations = [[NSMutableArray alloc] initWithCapacity:0];
            }
            [needRemoveConversations addObject:conversation.chatter];
        }
    }
    if (needRemoveConversations && needRemoveConversations.count > 0) {
        [[EaseMob sharedInstance].chatManager removeConversationsByChatters:needRemoveConversations
                                                             deleteMessages:YES
                                                                append2Chat:NO];
    }
}

- (void)removeChatroomConversationsFromDB
{
    NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations];
    NSMutableArray *needRemoveConversations;
    for (EMConversation *conversation in conversations) {
        if (conversation.conversationType == eConversationTypeChatRoom) {
            if (!needRemoveConversations) {
                needRemoveConversations = [[NSMutableArray alloc] initWithCapacity:0];
            }
            [needRemoveConversations addObject:conversation.chatter];
        }
    }
    
    if (needRemoveConversations && needRemoveConversations.count > 0) {
        [[EaseMob sharedInstance].chatManager removeConversationsByChatters:needRemoveConversations
                                                             deleteMessages:YES
                                                                append2Chat:NO];
    }
}

#pragma mark - getter

- (SRRefreshView *)slimeView
{
    if (!_slimeView) {
        _slimeView = [[SRRefreshView alloc] init];
        _slimeView.delegate = self;
        _slimeView.upInset = 0;
        _slimeView.slimeMissWhenGoingBack = YES;
        _slimeView.slime.bodyColor = APPCOLOR(1);
        _slimeView.slime.skinColor = [UIColor whiteColor];
        _slimeView.slime.lineWith = 1;
        _slimeView.slime.shadowBlur = 0;
        _slimeView.slime.shadowColor = [UIColor redColor];
    }
    
    return _slimeView;
}

//- (UISearchBar *)searchBar
//{
//    if (!_searchBar) {
//        _searchBar = [[EMSearchBar alloc] initWithFrame: CGRectMake(0, 0, self.view.frame.size.width, 44)];
//        _searchBar.delegate = self;
//        _searchBar.placeholder = NSLocalizedString(@"search", @"Search");
//        _searchBar.tintColor = APPCOLOR(1);
//        _searchBar.barTintColor = [UIColor blackColor];
////        _searchBar.barStyle = UIBarStyleBlackOpaque;
//        [_searchBar setBackgroundImage:[UIImage imageWithColor:RGBA(31, 30, 30, 1)]];// 搜索框样式
//        _searchBar.backgroundColor =  [UIColor blackColor];
//        [_searchBar setSearchBarStyle:UISearchBarStyleProminent];
//
//    }
//    
//    return _searchBar;
//}

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight) style:UITableViewStylePlain];
        _tableView.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
//        _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ChatListCell class] forCellReuseIdentifier:@"chatListCell"];
//        _tableView.tableHeaderView = _searchBar;
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 110, 0);//偏移量
        self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 110, 0);//滚动条偏移量
        self.tableView.separatorColor = [UIColor clearColor];//分隔条颜色

        
        headErrorView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, DeviceWidth, 44)];
        headErrorView.backgroundColor = RGBA(151, 196, 248, 0.95);
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, (headErrorView.frame.size.height - 20) / 2, 20, 20)];
        imageView.image = [UIImage imageNamed:@"messageSendFail"];
        [headErrorView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + 5, 0, headErrorView.frame.size.width - (CGRectGetMaxX(imageView.frame) + 15), headErrorView.frame.size.height)];
        label.font = [UIFont systemFontOfSize:15.0];
        label.textColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor clearColor];
        label.text = @"当前网络异常,下拉刷新重新";
        [headErrorView addSubview:label];
    }
    
    return _tableView;
}

- (EMSearchDisplayController *)searchController
{
    if (_searchController == nil) {
        _searchController = [[EMSearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
        _searchController.delegate = self;
        _searchController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        __weak ChatListViewController *weakSelf = self;
        [_searchController setCellForRowAtIndexPathCompletion:^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
            static NSString *CellIdentifier = @"ChatListCell";
            ChatListCell *cell = (ChatListCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            // Configure the cell...
            if (cell == nil) {
                cell = [[ChatListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            
            EMConversation *conversation = [weakSelf.searchController.resultsSource objectAtIndex:indexPath.row];
            cell.name = conversation.chatter;
            if (conversation.conversationType != eConversationTypeChat) {
                cell.placeholderImage = [UIImage imageNamed:@"chatListCellHead.png"];
            }
            else{
                NSString *imageName = @"groupPublicHeader";
                NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
                for (EMGroup *group in groupArray) {
                    if ([group.groupId isEqualToString:conversation.chatter]) {
                        cell.name = group.groupSubject;
                        imageName = group.isPublic ? @"groupPublicHeader" : @"groupPrivateHeader";
                        break;
                    }
                }
                cell.placeholderImage = [UIImage imageNamed:imageName];
            }
            cell.detailMsg = [weakSelf subTitleMessageByConversation:conversation];
            cell.time = [weakSelf lastMessageTimeByConversation:conversation];
            cell.unreadCount = [weakSelf unreadMessageCountByConversation:conversation];
            if (indexPath.row % 2 == 1) {
                cell.contentView.backgroundColor = RGBA(246, 246, 246, 1);
            }else{
                cell.contentView.backgroundColor = [UIColor whiteColor];
            }
            return cell;
        }];
        
        [_searchController setHeightForRowAtIndexPathCompletion:^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
            return [ChatListCell tableView:tableView heightForRowAtIndexPath:indexPath];
        }];
        [_searchController setDidSelectRowAtIndexPathCompletion:^(UITableView *tableView, NSIndexPath *indexPath) {
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            [weakSelf.searchController.searchBar endEditing:YES];
            
            EMConversation *conversation = [weakSelf.searchController.resultsSource objectAtIndex:indexPath.row];
            ChatViewController *chatVC = [[ChatViewController alloc] initWithChatter:conversation.chatter conversationType:conversation.conversationType];
            chatVC.delelgate = weakSelf;
            chatVC.title = conversation.chatter;
            [weakSelf.navigationController pushViewController:chatVC animated:YES];
        }];
    }
    
    return _searchController;
}


#pragma mark - private

- (NSMutableArray *)loadDataSource
{
    NSMutableArray *ret = nil;
    NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations];
    
    NSArray* sorte = [conversations sortedArrayUsingComparator:
                      ^(EMConversation *obj1, EMConversation* obj2){
                          EMMessage *message1 = [obj1 latestMessage];
                          EMMessage *message2 = [obj2 latestMessage];
                          if(message1.timestamp > message2.timestamp) {
                              return(NSComparisonResult)NSOrderedAscending;
                          }else {
                              return(NSComparisonResult)NSOrderedDescending;
                          }
                      }];
    
    ret = [[NSMutableArray alloc] initWithArray:sorte];
    return ret;
}


// 加载约会列表
//- (void)loadDateList {
//    //那么需要加载约会申请列表
//    MLUser *currentUser = [MLUser currentUser];
//        AVQuery *dateApplyQuery = [MLDate query];
//        [dateApplyQuery whereKey:@"user" equalTo:currentUser];
//        [dateApplyQuery includeKey:@"sponsor"];
//        [dateApplyQuery whereKey:@"status" equalTo:[NSNumber numberWithInt:MLDateStatus_APPLYING]];
//        [dateApplyQuery orderByDescending:@"updatedAt"];
//        [dateApplyQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
//            if (!error) {
//                self.dateApplyList = [[NSMutableArray alloc]initWithArray:objects];
//            }
//        }];
//    
//    // 用户发起的约会申请列表
//    AVQuery *dateLaunchQuery = [MLDate query];
//    [dateLaunchQuery whereKey:@"sponsor" equalTo:currentUser];
//    [dateLaunchQuery includeKey:@"user"];
//    [dateLaunchQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
//        if (!error) {
//            self.dateLaunchList = [[NSMutableArray alloc]initWithArray:objects];
//        }
//    }];
//}

// 得到最后消息时间
-(NSString *)lastMessageTimeByConversation:(EMConversation *)conversation
{
    NSString *ret = @"";
    EMMessage *lastMessage = [conversation latestMessage];;
    if (lastMessage) {
        ret = [NSDate formattedTimeFromTimeInterval:lastMessage.timestamp];
    }
    
    return ret;
}

// 得到未读消息条数
- (NSInteger)unreadMessageCountByConversation:(EMConversation *)conversation
{
    NSInteger ret = 0;
    ret = conversation.unreadMessagesCount;
    msgUnreadCount += ret;
    if (msgUnreadCount == 0) {
//        [[[[[self tabBarController] viewControllers] objectAtIndex: 1] tabBarItem] setBadgeValue:nil];
        UIView *Badge = (UIView*)[self.tabBarController.tabBar viewWithTag:100001];
        if (Badge.alpha == 1) {
            [Utils Hidden:Badge Bool:NO];
        }
    }else{
//        [[[[[self tabBarController] viewControllers] objectAtIndex: 1] tabBarItem] setBadgeValue:[NSString stringWithFormat:@"%ld",(long)msgUnreadCount]];
    }
    
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:msgUnreadCount forKey:@"unreadMsg"];
    [defaults synchronize];
    
    return  ret;
}

// 得到最后消息文字或者类型
-(NSString *)subTitleMessageByConversation:(EMConversation *)conversation
{
    NSString *ret = @"";
    EMMessage *lastMessage = [conversation latestMessage];
    if (lastMessage) {
        id<IEMMessageBody> messageBody = lastMessage.messageBodies.lastObject;
        
        if ([[messageBody.message.ext objectForKey:@"notification"]isEqualToString:EMMESSAGE_EXT_TYPE_BURN_AFTER_READ_MSG]) {
            ret = @"[私密消息]";
        }
        
        switch (messageBody.messageBodyType) {
            case eMessageBodyType_Image:{
                ret = NSLocalizedString(@"message.image1", @"[image]");
            } break;
            case eMessageBodyType_Text:{
                // 表情映射。
                NSString *didReceiveText = [ConvertToCommonEmoticonsHelper
                                            convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                ret = didReceiveText;
            } break;
            case eMessageBodyType_Voice:{
                ret = NSLocalizedString(@"message.voice1", @"[voice]");
            } break;
            case eMessageBodyType_Location: {
                ret = NSLocalizedString(@"message.location1", @"[location]");
            } break;
            case eMessageBodyType_Video: {
                ret = NSLocalizedString(@"message.vidio1", @"[vidio]");
            } break;
            default: {
            } break;
        }
        
        
    }
    
    return ret;
}

#pragma mark - call control


#pragma mark - TableViewDelegate & TableViewDatasource

-(UITableViewCell *)tableView:(UITableView *)tableView
        cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identify = @"chatListCell";
    ChatListCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    
    if (!cell) {
        cell = [[ChatListCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identify];
    }
    EMConversation *conversation = [self.dataSource objectAtIndex:indexPath.row];
    EMMessage *lastMessage = [conversation latestMessage];
    
    
    if ([lastMessage.to isEqualToString:@"mlsystem"]||[lastMessage.from isEqualToString:@"mlsystem"]) {
        NSMutableAttributedString *mString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"无独团"]];
        cell.attributedName = mString;
        //cell.name = @"无独团";
        cell.placeholderImage = [UIImage imageNamed:@"common_koudai_icon"];
        cell.imageURL = [NSURL URLWithString:@""];

        // TODO
        cell.detailMsg = [self subTitleMessageByConversation:conversation];
        cell.time = [self lastMessageTimeByConversation:conversation];
        cell.unreadCount = [self unreadMessageCountByConversation:conversation];
        return cell;
    }
    // 推荐的恋人有通话申请
    if ([lastMessage.from isEqualToString:@"new_friend"]||[lastMessage.to isEqualToString:@"new_friend"]) {
        NSMutableAttributedString *mString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"新的好友"]];
        cell.attributedName = mString;
       // cell.name = @"新的好友";
        cell.placeholderImage = [UIImage imageNamed:@"common_new_icon"];
        cell.imageURL = [NSURL URLWithString:@""];

        // TODO
        cell.detailMsg = [self subTitleMessageByConversation:conversation];
        cell.time = [self lastMessageTimeByConversation:conversation];
        cell.unreadCount = [self unreadMessageCountByConversation:conversation];
        return cell;
    }
    // 新的爱人
    if ([lastMessage.from isEqualToString:@"new_sweet"]||[lastMessage.to isEqualToString:@"new_sweet"]) {
       
        NSMutableAttributedString *mString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"试恋申请"]];
        cell.attributedName = mString;
        //cell.name = @"新的试恋";
        cell.placeholderImage = [UIImage imageNamed:@"新的恋人"];
        cell.imageURL = [NSURL URLWithString:@""];
        
        // TODO
        cell.detailMsg = [self subTitleMessageByConversation:conversation];
        cell.time = [self lastMessageTimeByConversation:conversation];
        cell.unreadCount = [self unreadMessageCountByConversation:conversation];
        return cell;
    }

    // 系统消息
    MLUser *chatUser = [[ShareData shareData].chatterUsers objectForKey:conversation.chatter];
    
    if (conversation.conversationType == eConversationTypeChat) {
        
        
        if (!chatUser) {
            NSDictionary *userDic = [Utils getUserNicknameHeadurlObjectId:conversation.chatter];
            if (userDic) {
                _tableView.tableHeaderView = nil;
                NSString *nickname = [userDic objectForKey:@"nickname"];
                NSString *headurl = [userDic objectForKey:@"headurl"];
                // 指定正确地聊天对象
                NSMutableAttributedString *mString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",nickname]];
                cell.attributedName = mString;
               // cell.name = nickname;
            
                cell.placeholderImage = [UIImage imageNamed:@"default_portrait"];
                cell.imageURL = [NSURL URLWithString: headurl];
                
            }else{
                 NSMutableAttributedString *mString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",@""]];
                cell.attributedName = mString;
               // cell.name = @"";
                cell.placeholderImage = [UIImage imageNamed:@"default_portrait"];
               _tableView.tableHeaderView = headErrorView;
            }
        }else{
            _tableView.tableHeaderView = nil;
          //  NSString *title = [NSString stringWithFormat:@"%@",chatUser.nickname];
            // 指定正确地聊天对象
            if ([Utils isSweetheartObjectId:chatUser.objectId]) {
                NSMutableAttributedString *mString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"[试恋] %@",chatUser.nickname]];
                [mString addAttribute:NSForegroundColorAttributeName value:RGBA(250, 121, 151, 1) range:NSMakeRange(0,4)];
                [mString addAttribute:NSFontAttributeName value:kFont(15) range:NSMakeRange(0,4)];
                cell.attributedName = mString;
            }else if([Utils isFriendObjectId:chatUser.objectId]){
                NSMutableAttributedString *mString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",chatUser.nickname]];
               // [mString addAttribute:NSForegroundColorAttributeName value:RGBA(72, 119, 172, 1) range:NSMakeRange(0,4)];
               // [mString addAttribute:NSFontAttributeName value:kFont(15) range:NSMakeRange(0,4)];
                cell.attributedName = mString;
               // cell.name = [NSString stringWithFormat:@"%@",chatUser.nickname];
                
            }else{
                NSMutableAttributedString *mString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"[陌生人] %@",chatUser.nickname]];
                [mString addAttribute:NSForegroundColorAttributeName value:RGBA(212, 212, 212, 1) range:NSMakeRange(0,5)];
                [mString addAttribute:NSFontAttributeName value:kFont(15) range:NSMakeRange(0,5)];
                cell.attributedName = mString;
               // cell.name = [NSString stringWithFormat:@"[陌生人] %@",chatUser.nickname];
            }
            
            cell.placeholderImage = [UIImage imageNamed:@"default_portrait"];
            if (!chatUser.subAvatar || [chatUser.subAvatar isEqualToString:@""]) {
                cell.imageURL = [NSURL URLWithString: chatUser.avatar.url];
            }else{
                cell.imageURL = [NSURL URLWithString: chatUser.subAvatar];
            }
        }
        
        
    }
    else{
        NSString *imageName = @"groupPublicHeader";
        if (![conversation.ext objectForKey:@"groupSubject"] || ![conversation.ext objectForKey:@"isPublic"])
        {
            NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
            for (EMGroup *group in groupArray) {
                if ([group.groupId isEqualToString:conversation.chatter]) {
                    
                    NSMutableAttributedString *mString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",group.groupSubject]];
                    cell.attributedName = mString;
                    imageName = group.isPublic ? @"groupPublicHeader" : @"groupPrivateHeader";
                    
                    NSMutableDictionary *ext = [NSMutableDictionary dictionaryWithDictionary:conversation.ext];
                    [ext setObject:group.groupSubject forKey:@"groupSubject"];
                    [ext setObject:[NSNumber numberWithBool:group.isPublic] forKey:@"isPublic"];
                    conversation.ext = ext;
                    break;
                }
            }
        }
        else
        {
            cell.name = [conversation.ext objectForKey:@"groupSubject"];
            imageName = [[conversation.ext objectForKey:@"isPublic"] boolValue] ? @"groupPublicHeader" : @"groupPrivateHeader";
        }
        cell.placeholderImage = [UIImage imageNamed:imageName];
    }
    cell.detailMsg = [self subTitleMessageByConversation:conversation];
    cell.time = [self lastMessageTimeByConversation:conversation];
    cell.unreadCount = [self unreadMessageCountByConversation:conversation];
    
    
    if (indexPath.row % 2 == 1) {
        cell.contentView.backgroundColor = RGBA(246, 246, 246, 1);
    }else{
        cell.contentView.backgroundColor = [UIColor whiteColor];
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.dataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [ChatListCell tableView:tableView heightForRowAtIndexPath:indexPath];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 通话申请
    EMConversation *conversation = [self.dataSource objectAtIndex:indexPath.row];
    EMMessage *lastMessage = [conversation latestMessage];
    MLUser *chatUser = [[ShareData shareData].chatterUsers objectForKey:conversation.chatter];
     NSDictionary *userDic = [Utils getUserNicknameHeadurlObjectId:conversation.chatter];
    if (!chatUser) {
        if (!([lastMessage.to isEqualToString:@"mlsystem"]||[lastMessage.from isEqualToString:@"mlsystem"]) && !([lastMessage.to isEqualToString:@"new_friend"]||[lastMessage.from isEqualToString:@"new_friend"])&& !([lastMessage.to isEqualToString:@"new_sweet"]||[lastMessage.from isEqualToString:@"new_sweet"])) {
           
            if (userDic){
                //用户信息已经存储了
            }else{
                [HUD Prompt:@"当前网络异常,下拉刷新重新"];
                return;
            }
        }else{
           
        }
    }
   
    
    
    if ([lastMessage.to isEqualToString:@"new_friend"]||[lastMessage.from isEqualToString:@"new_friend"]) {
        [conversation markAllMessagesAsRead:YES];
        FriendApplyViewController *callApplyVC = [[FriendApplyViewController alloc]init];
        callApplyVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:callApplyVC animated:YES];
        return;
    }
    
    // 新的爱人
    if ([lastMessage.from isEqualToString:@"new_sweet"]||[lastMessage.to isEqualToString:@"new_sweet"]) {
        [conversation markAllMessagesAsRead:YES];
        SweetheartApplyViewController *callApplyVC = [[SweetheartApplyViewController alloc]init];
        callApplyVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:callApplyVC animated:YES];
        return;
    }
    
    ChatViewController *chatController;
    
    NSString *title = conversation.chatter;
    if (conversation.conversationType != eConversationTypeChat) {
        if ([[conversation.ext objectForKey:@"groupSubject"] length])
        {
            title = [conversation.ext objectForKey:@"groupSubject"];
        }
        else
        {
            NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
            for (EMGroup *group in groupArray) {
                if ([group.groupId isEqualToString:conversation.chatter]) {
                    title = group.groupSubject;
                    break;
                }
            }
        }
    }
    NSString *chatter ;
    if ([lastMessage.to isEqualToString:@"mlsystem"]||[lastMessage.from isEqualToString:@"mlsystem"]) {
        chatter = @"mlsystem";
        [AVAnalytics event:@"无独团"]; // 通知服务器一个点击事件。
    }else{
        chatter = conversation.chatter;
    }
    chatController = [[ChatViewController alloc] initWithChatter:chatter conversationType:conversation.conversationType];
    chatController.delelgate = self;
    if (chatUser) {
        chatController.chatUser = chatUser;
        chatController.title = chatUser.nickname;
    }else{
        if (userDic) {
            NSString *nickname = [userDic objectForKey:@"nickname"];
            chatController.title = nickname;
            chatController.isNullChatUser = YES;
        }else{
            if ([lastMessage.to isEqualToString:@"mlsystem"]||[lastMessage.from isEqualToString:@"mlsystem"]) {
            
                
            }else{
                [HUD Prompt:@"当前消息列表加载错误,下拉刷新重新"];
                return;
            }
            
            
        }
        
    }
    
    
    
    chatController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:chatController animated:YES];
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        EMConversation *converation = [self.dataSource objectAtIndex:indexPath.row];
        [[EaseMob sharedInstance].chatManager removeConversationByChatter:converation.chatter deleteMessages:YES append2Chat:YES];
        if (self.dataSource&&self.dataSource.count) {
            [self.dataSource removeObjectAtIndex:indexPath.row];
        }
        
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

#pragma mark - UISearchBarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [searchBar setShowsCancelButton:YES animated:YES];
    
    return YES;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    __weak typeof(self) weakSelf = self;
    [[RealtimeSearchUtil currentUtil] realtimeSearchWithSource:self.dataSource searchText:(NSString *)searchText collationStringSelector:@selector(chatter) resultBlock:^(NSArray *results) {
        if (results) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.searchController.resultsSource removeAllObjects];
                [weakSelf.searchController.resultsSource addObjectsFromArray:results];
                [weakSelf.searchController.searchResultsTableView reloadData];
            });
        }
    }];
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = @"";
    [[RealtimeSearchUtil currentUtil] realtimeSearchStop];
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:NO animated:YES];
}

#pragma mark - scrollView delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_slimeView scrollViewDidScroll];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [_slimeView scrollViewDidEndDraging];
}


#pragma mark - slimeRefresh delegate
//刷新消息列表
- (void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView
{
    if (![[EaseMob sharedInstance].chatManager isConnected]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginEaseMob" object:self userInfo:nil];
    }
    [self refreshDataSource];
    [self registerNotifications];
    userCount = self.dataSource.count;
    NSMutableArray *userIds = [[NSMutableArray alloc]init];
    for (EMConversation *conversation in self.dataSource) {
        [userIds addObject:conversation.chatter];
    }
    AVQuery *userQuery = [MLUser query];
    userQuery.cachePolicy = kAVCachePolicyNetworkElseCache;
    userQuery.maxCacheAge = 7200;
    [userQuery whereKey:@"objectId" containedIn:userIds];
    [userQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            for (MLUser *user in objects) {
                [[ShareData shareData].chatterUsers setObject:user forKey:user.objectId];
                [Utils saveChatUserDataNicknameUser:user];
            }
            msgUnreadCount = 0;
            [self.tableView reloadData];
            self.title = @"消息";
        }else{
          //  self.title = @"消息(获取失败)";
        }
        
    }];
    
    [_slimeView endRefresh];
}

#pragma mark - IChatMangerDelegate

-(void)didUnreadMessagesCountChanged
{
    [self refreshDataSource];
}

- (void)didUpdateGroupList:(NSArray *)allGroups error:(EMError *)error
{
    [self refreshDataSource];
}

#pragma mark - registerNotifications
-(void)registerNotifications{
    [self unregisterNotifications];
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
}

-(void)unregisterNotifications{
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
}

- (void)dealloc{
    [self unregisterNotifications];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - public

-(void)refreshDataSource
{
    self.dataSource = [self loadDataSource];
    [self laixiaoxi];
    msgUnreadCount = 0;
    [_tableView reloadData];
    [self hideHud];
    if ([self.dataSource count] == 0) {
        promptView.viewPrompt.alpha = 1;
    }else{
        promptView.viewPrompt.alpha = 0;
    }
}

- (void)networkChanged:(EMConnectionState)connectionState
{
    if (connectionState == eEMConnectionDisconnected) {
        [Utils plistName:NSLocalizedString(@"network.disconnection", @"Network disconnection")];
    }
    else{
        [self refreshDataSource];
    }
}

- (void)willReceiveOfflineMessages{
    NSLog(NSLocalizedString(@"message.beginReceiveOffine", @"Begin to receive offline messages"));
}

- (void)didReceiveOfflineMessages:(NSArray *)offlineMessages
{
    [self refreshDataSource];
}

- (void)didFinishedReceiveOfflineMessages:(NSArray *)offlineMessages{
    NSLog(NSLocalizedString(@"message.endReceiveOffine", @"End to receive offline messages"));
    [self refreshDataSource];
}


#pragma mark - user interaction
//- (void)startPrivateChat:(MLUser *)user is:(BOOL)is{
//    // 添加到聊天对象字典
//    [self.chatterUsers setObject:user forKey:user.objectId];
//    // 跳转到聊天页面
//    ChatViewController *chatVC = [[ChatViewController alloc]initWithChatter:user.objectId isGroup:NO];
//    chatVC.chatUser = user;
//    chatVC.is = is;
//    chatVC.title = user.nickname;
//    chatVC.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:chatVC animated:YES];
//}
// 根据环信id得到要显示头像路径，如果返回nil，则显示默认头像
- (NSString *)avatarWithChatter:(NSString *)chatter{
    //    return @"http://img0.bdstatic.com/img/image/shouye/jianbihua0525.jpg";
    return nil;
}

// 根据环信id得到要显示用户名，如果返回nil，则默认显示环信id
- (NSString *)nickNameWithChatter:(NSString *)chatter{
    return chatter;
}
//用户类型改变,
- (void)chatUserTypeDataChangeUser:(MLUser *)chatUser
{
    
    [[ShareData shareData].chatterUsers setObject:chatUser forKey:chatUser.objectId];
    [Utils saveChatUserDataNicknameUser:chatUser];
    if ([ShareData shareData].friends) {
        //判断是否已经是好友
        for (int i = 0; i<[ShareData shareData].friends.count; i++) {
            MLUser *f = (MLUser *)[ShareData shareData].friends[i];
            if([f.objectId isEqualToString:chatUser.objectId]){
                [[ShareData shareData].friends replaceObjectAtIndex:i withObject:chatUser];
                [Utils savePassFriendObjectID:chatUser.objectId];
                break;
            }
        }
    }
    NSDictionary *dic=@{@"user":chatUser};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"chatUserTypeDataChange" object:self userInfo:dic];
}
- (void)startPrivateChat:(MLUser *)user{
    // 添加到聊天对象字典
    [[ShareData shareData].chatterUsers setObject:user forKey:user.objectId];
    [Utils saveChatUserDataNicknameUser:user];
    // 跳转到聊天页面
    ChatViewController *chatVC = [[ChatViewController alloc]initWithChatter:user.objectId isGroup:NO];
    chatVC.delelgate = self;
    chatVC.chatUser = user;
    chatVC.title = user.nickname;
    chatVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:chatVC animated:YES];
}

@end
